package cn.codeim;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //这里进行转换，因为ByteBuf提供了更强大灵活的功能
        ByteBuf buf = (ByteBuf) msg;
        //readableBytes()方法可以获取缓冲区可读的字节数，以此创建一个合适大小的byte数组
        byte[] bytes = new byte[buf.readableBytes()];
        //readBytes方法将buf中缓存的字节复制到新建的bytes数组中
        buf.readBytes(bytes);
        //将数组转为字符
        String s = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("The time is " + s + ";the counter is " + ++counter);
        //QUERY TIME ORDER这串字符是客户端发送过来的，这里判断请求消息来源，如果是客户端的消息，则将正确时间赋值给currentTime
        String currentTime = ("QUERY TIME ORDER" + System.lineSeparator()).equalsIgnoreCase(s) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
        //转为ByteBuf对象
        ByteBuf byteBuf = Unpooled.copiedBuffer(currentTime.getBytes());
        //异步发送应答消息给客户端
        ctx.write(byteBuf);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
